const md = require('../../utils/md5.js');
const app = getApp();
const post = require('../../utils/post.js');
var util = require('../../utils/util.js');
var loading = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    lastlist: [],
    srctype: "全部",
    customItem: '全部',
    isending:0,
    array: [{
        'name': '全部',
        state: 1
      },
      {
        'name': '未提交',
        state: 0
      },
      {
        'name': '已审核',
        state: 100
      },
      {
        'name': '提交审核',
        state: 10
      },
      {
        'name': '初审通过',
        state: 20
      },
      {
        'name': '审批退回',
        state: 5
      },
      {
        'name': '商户申请',
        state: 30
      },
      {
        'name': '商户申请失败',
        state: 15
      },
      {
        'name': '门店失效',
        state: -10
      },
    ],
    index: 0,
    key: '',
    saindex: 0,
    saarray: [{
        'name': '全部',
        'value': 3
      },
      {
        'name': '活跃',
        'value': 1
      },
      {
        'name': '不活跃',
        'value': 0
      }
    ],
    puindex: 0,
    puarray: [{
        'name': '全部',
        'value': 3
      },
      {
        'name': '活跃',
        'value': 1
      },
      {
        'name': '不活跃',
        'value': 0
      }
    ],
    model: 0,
    pageindex:1,
    pagesize:10,
    pagecount:null,
    cityarray:'地区',
    nums:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var time = util.formatTime(new Date());
    time = time.split(' ')[0];
    time = time.split('-');
    var timearr = time[0] + '-' + time[1];

    wx.getSystemInfo({
      success: function(res) {
        console.log(res.windowHeight);
        that.setData({
          scrollHeight: res.windowHeight - 100,
          firstday: timearr + '-01',
          today: time[0] + '-' + time[1] + "-" + time[2],
          showfirst: timearr,
          endday: time[0] + '-' + time[1] + "-" + time[2],
        })
      },
    })

    //  var city = userinfo.ProName + "/" + userinfo.CityName + "/" + "全部";
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },
  onShow:function(){
    var that = this;
    this.setData({
      pageindex: 1,
      pagesize: 10,
      pagecount: null,
    })
    let cityname = wx.getStorageSync('userinfo').CityName;
    if(cityname){
      this.setData({
        cityname:cityname
      })
    }else{
      cityname='';
    }
    console.log(cityname);
    this.getareaarray();
    that.newsearch(cityname, 1);
  },
  bindcityChange: function (e) {
    var that = this;
    console.log(that.data.cityarray[e.detail.value]);
    that.setData({
      cityname: that.data.cityarray[e.detail.value].id,
      pageindex: 1,
      pagesize: 10,
      pagecount: null,
    })
    that.newsearch(that.data.cityarray[e.detail.value].id,1)
  },
  getareaarray: function () {
    var that = this;
    var datas = {};
    var datacall = function (res) {
      console.log(res);
      if (res.data.data.length > 0) {
        var obj = {};
        var arr = [{name:'全部',id:"全部"}];
        for (var i = 0; i < res.data.data.length; i++) {
          obj.name = res.data.data[i].CityName;
          obj.id = res.data.data[i].CityName;
          arr[i] = obj;
          obj = {};
        }
        that.setData({
          cityarray: arr
        })
      }
    }
    var res2 = post.getdata("/BO/V_UsingCitys/Query", datas, datacall);
  },
  searchstore: function() {
    this.setData({
      model: 0,
      pageindex: 1,
      pagesize: 10,
      pagecount: null,
    })
    this.newsearch(0,1)
  },
  search: function(city) {
    var that = this;
    var state = that.data.state;
    var datas = {};
    var where = "ServiceMebID = " + wx.getStorageSync('userinfo').MebID;
    if (city) {
      var proname = city.split('/')[0];
      var cityname = city.split('/')[1];
      var areaname = city.split('/')[2];
      if (cityname == '全部') {
        cityname = '';
      }
      if (areaname == '全部') {
        areaname = '';
      }
      where += " and ProName like '%" + proname + "%' and CityName like '%" + cityname + "%' and AreaName like '%" + areaname + "%'";
    }
    var key = that.data.key;
    if (key) {
      where += " and (AccName like '%" + key + "%' or MasterMebName like '%" + key + "%')";
    }

    if (state || state == 0) {
      if (state != 'all') {
        where += " and ApplyBOState =" + state;
      }

    }
    console.log(where);
    datas.where = where;
    var datacall = function(res) {
      console.log(res);
      that.setData({
        lastlist: res.data.data
      })
    }
    var res2 = post.getdata("/BO/TR_Account/Query", datas, datacall);
  },
  newsearch: function(cityname = '',isnew=0) {
    var that = this;
    loading++;
    if(loading!=1){
      return;
    }
    var datas = {};
    datas.where = "CurrSMebID = null";
    console.log(cityname);
    if(cityname){
      if (cityname != '地区' && cityname != '全部' && cityname != '0') {
        datas.where += " and CityName like '%" + cityname + "%'";
      }
    }else{
      if (that.data.cityname != '地区' && that.data.cityname != '全部' && that.data.cityname != '0') {
        datas.where += " and CityName like '%" + that.data.cityname + "%'";
      }
    }
    
    if(that.data.putype){
      if(that.data.putype=='活跃'){
        datas.where+=" and IsPUActive = 1";
      } else if (that.data.putype == '不活跃'){
        datas.where += " and IsPUActive = 0";
      }
    }
    if (that.data.satype) {
      if (that.data.satype == '活跃') {
        datas.where += " and IsSAActive = 1";
      } else if(that.data.satype == '不活跃'){
        datas.where += " and IsSAActive = 0";
      }
    }
    datas.pageindex =that.data.pageindex;
    datas.pagesize = that.data.pagesize;
    if (that.data.key) {
      datas.where += " and AccName like '%" + that.data.key + "%' ";
    }
    console.log(datas);
    var datacall = function(res) {
      console.log(res);
      setTimeout(()=>{
        wx.hideLoading()
      },1000);
      
      var list = res.data.data;
      var satotal = 0;
      var sanum = 0;
      var putotal = 0;
      var punum = 0;
      var shopnum = list.length;
      var lastlist = that.data.lastlist;
      for (var i = 0; i < list.length; i++) {
        list[i].SASumMny = post.toDecimal2(list[i].SASumMny);
        list[i].PUSumMny = post.toDecimal2(list[i].PUSumMny);
        // if (isfirst == 1) {
        satotal += list[i].SASumMny;
        sanum += list[i].SASumCount;
        putotal += list[i].PUSumMny;
        punum += list[i].PUSumCount;
        // }
        if (list[i].AccName.length > 10) {
          list[i].AccNames = list[i].AccName.substring(0, 9) + "...";
        } else {
          list[i].AccNames = list[i].AccName;
        }
        lastlist.push(list[i]);
      }
      var sato = satotal + '';
      sato = sato.split('.');
      if (sato[0].length > 5) {
        satotal = satotal / 10000;
        satotal = satotal.toFixed(2);
        satotal = satotal + '万元';
      } else {
        satotal = parseInt(satotal) + '元';
      }
      putotal = parseInt(putotal);
      if(isnew){
        lastlist = list;
      }
      that.setData({
        satotal: satotal,
        sanum: sanum,
        putotal: putotal,
        punum: punum,
        shopnum: shopnum,
        lastlist: lastlist,
        pageindex:that.data.pageindex+1,
        pagecount:res.data.pagecount,
        nums: res.data.totalcount

      })
      loading = 0;

    }
    var res2 = post.getdata("/BO/PE_ShopStatus/Query", datas, datacall);
  },

  //开店申请状态选择
  bindPickerChange: function(e) {
    console.log(this.data.array[e.detail.value])
    this.setData({
      index: e.detail.value,
      srctype: this.data.array[e.detail.value].name,
      state: this.data.array[e.detail.value].state
    })
    // this.newsearch();
  },
  bindSAChange: function(e) {
    console.log(this.data.saarray[e.detail.value])
    this.setData({
      saindex: e.detail.value,
      satype: this.data.saarray[e.detail.value].name,
      sastate: this.data.saarray[e.detail.value].value
    })
    // this.newsearch();
  },
  bindPUChange: function(e) {
    console.log(this.data.puarray[e.detail.value])
    this.setData({
      puindex: e.detail.value,
      putype: this.data.puarray[e.detail.value].name,
      pustate: this.data.puarray[e.detail.value].value
    })
    // this.newsearch();

  },
  bindDateChange: function(e) {
    var that = this;
    var time = e.detail.value.split('-');
    var d = new Date(time[0], time[1], 0);
    that.setData({
      firstday: e.detail.value + "-1",
      endday: e.detail.value + "-" + d.getDate(),
      showfirst: e.detail.value
    })
  },
  tolinkman: function(e) {
    wx.navigateTo({
      url: '/pages/linkman/linkman?id=' + e.currentTarget.dataset.id,
    })
  },
  getkey: function(e) {
    this.setData({
      key: e.detail.value
    })
  },
  clearall: function() {
    var that = this;
    that.setData({
      key: ''
    });
    that.searchstore()
  },
  newdata: function(e) {
    var that = this;
    if((that.data.pageindex - 1) == that.data.pagecount){
     that.setData({
       isending:1
     })
      return;
    }
    wx.showLoading({
      title: '加载中...',
    })
    that.newsearch();
  },
  saoyisao: function() {
    var that = this;
    wx.scanCode({
      success: (res) => {
        console.log(res.result);
        var data = res.result.split('&');
        var mebarr = data[0].split(':');
        if (mebarr[0] == 'mebid' && mebarr[1] != '') {
          console.log(data)
          var datas = {};
          if (data[1]) {
            var depid = data[1].split(':')[1];
          } else {
            var depid = '';
          }

          if (!depid) {
            wx.showModal({
              title: '',
              content: '对方还未提交审核，无法添加',
            })
          }
          datas.where = "AccID = " + depid;
          var datacall = function(res) {
            console.log(res);
            if (res.data.data.length != 0) {
              if (res.data.data[0].ServiceMebID) {
                wx.showModal({
                  title: '',
                  content: '对方已经有客户经理，无法添加',
                })
                return;
              } else {
                console.log("oktian");
                that.addservice(depid);
              }
            }
          }
          var res2 = post.getdata("/BO/TR_Account/Query", datas, datacall);

        } else {
          wx.showModal({
            title: '',
            content: '不是符合规定的二维码',
          })
        }
      }
    })
  },
  //添加服务门店
  addservice: function(id) {
    var that = this;
    var datas = {};
    var data = {};
    data.AccID = id;
    data.ServiceMebID = wx.getStorageSync('mebid');
    datas.data = JSON.stringify(data);
    var datacall = function(res) {
      console.log(res);
      wx.showModal({
        title: '',
        content: '添加服务门店成功！',
      })
      var city = that.data.date;
      that.search(city)
    }
    var res2 = post.getdata("/BO/TR_Account/Modify", datas, datacall);
  },
  closemodel: function() {
    this.setData({
      model: 0
    })
  },
  showchoose: function() {
    this.setData({
      model: 1
    })
  },
})